using System;
using Gtk;
using System.Xml;
using pointmass;

public partial class MainWindow : Gtk.Window
{
	/** is the sytem is playing on screen */
	bool Playing { get; set; }
	
	/** the system specification (initial condition) in xml format */
	XmlDocument m_xml = new XmlDocument ();
	
	/** Context for status bar messages */
	enum StatusContext : uint {PARSE_DONE, PARSE_FAILED};
	
	/** the mechanical system */
	MechanicSystem m_system = new MechanicSystem ();
	
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		Playing = false;
	}

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
	
	protected virtual void OnQuit (object sender, System.EventArgs e)
	{
		Application.Quit ();
	}
		
	protected virtual void OnPlay (object sender, System.EventArgs e)
	{
		Playing = !Playing;
		if (!Playing) {
			btnPlay.Label = "Play";
		}
		else {
			btnPlay.Label = "Pause";
		}
	}
	
	protected virtual void OnLoad (object sender, System.EventArgs e)
	{
		FileChooserDialog chooser = new FileChooserDialog(
		    "Choose a XML system specification file ...", this, FileChooserAction.Open, 
		    "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
		
		if (chooser.Run() == (int) ResponseType.Accept) 
		{
			System.IO.StreamReader file = System.IO.File.OpenText(chooser.Filename);
			m_xml.Load (file);
			if (ParseXML ())
			{
				m_system.Draw(txtSystemXML);
			}
			
			//txtSystemXML.Buffer.Text = m_xml.InnerXml ;
			file.Close ();
		}		
		chooser.Destroy ();		
	}
	
	protected bool ParseXML ()
	{
		XmlNodeList systemNodeList = m_xml.GetElementsByTagName("system");
		int count = systemNodeList.Count;
		if (count < 1) {
			stsBar.Push ((uint)StatusContext.PARSE_FAILED, string.Format ("No system found {0}", count));
			return false;
		}
		XmlNode systemNode = systemNodeList.Item (0);
		m_system.LoadSystemXml (systemNode);

		stsBar.Push ((uint)StatusContext.PARSE_DONE, string.Format ("System found {0}, number of objects {1}", count, m_system.Count));
		return true;
	}
	
}

